import { defineConfig, type UserConfigExport } from '@tarojs/cli'
import path from 'path'
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin'
import devConfig from './dev'
import prodConfig from './prod'

// https://taro-docs.jd.com/docs/next/config#defineconfig-辅助函数
export default defineConfig(async (merge) => {
    const baseConfig: UserConfigExport = {
        projectName: 'miniprogram',
        date: '2024-4-17',
        designWidth: 750,
        deviceRatio: {
            640: 2.34 / 2,
            750: 1,
            375: 2,
            828: 1.81 / 2
        },
        sourceRoot: "src",
        // outputRoot: "dist", , '@tarojs/plugin-platform-kwai'
        outputRoot: `dist/${process.env.NODE_ENV}/${process.env.TARO_ENV}`,
        plugins: ["@tarojs/plugin-html", "@tarojs/plugin-platform-tt", "@tarojs/plugin-platform-weapp"],
        defineConstants: {
        },
        sass: {
            data: `@import "@nutui/nutui-react-taro/dist/styles/variables.scss";`,
        },
        copy: {
            patterns: [

                {
                    from: "public",
                    to: "dist"
                }
            ],
            options: {}
        },
        framework: 'react',
        quiet: true,
        devServer: {
            client: {
                logging: 'error', // 关闭 Webpack 相关警告
                quiet: true
            },
        },
        compiler: {
            type: 'webpack5',
            prebundle: {
                // exclude: ['ossaui'],  // todo 引入ossaui
                enable: false // Webpack 持久化缓存配置，建议开启。默认配置请参考：https://docs.taro.zone/docs/config-detail#cache
            }
        },
        alias: {
            "@": path.resolve(__dirname, "..", "src"),
            lodash: 'lodash-es',
        },
        cache: {
            enable: false // Webpack 持久化缓存配置，建议开启。默认配置请参考：https://docs.taro.zone/docs/config-detail#cache
        },
        mini: {
            webpackChain(chain, webpack) {
                chain.output.chunkFilename('[name].[fullhash:8].js');
                chain.plugin('mini_define').use(webpack.DefinePlugin, [
                    {
                        global: 'globalThis',
                    },
                ]);
                chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin)
                chain.merge({
                    performance: {
                        hints: false
                    },
                })
            },
            experimental: {
                compileMode: true,
            },
            enableSourceMap: false,
            miniCssExtractPluginOption: {
                ignoreOrder: true
            },
            lessLoaderOption: {
                lessOptions: {
                    modifyVars: {
                        hack: 'true; @import "@/common/assets/css/variables.less";'
                    }
                }
            },
            postcss: {
                pxtransform: {
                    enable: true,
                    config: {
                        selectorBlackList: ["nut-"]
                    }
                },
                url: {
                    enable: true,
                    config: {
                        limit: 1024 // 设定转换尺寸上限
                    }
                },
                cssModules: {
                    enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
                    config: {
                        namingPattern: 'module', // 转换模式，取值为 global/module
                        generateScopedName: '[name]__[local]___[hash:base64:5]'
                    }
                }
            },
        },
        h5: {
            devServer: {
                client: {
                    logging: 'error',
                    overlay: false, // 关闭错误和警告的 overlay 层
                }
            },
            publicPath: '/',
            staticDirectory: 'static',
            router: {
                mode: 'browser'
            },
            output: {
                filename: 'js/[name].[hash:8].js',
                chunkFilename: 'js/[name].[chunkhash:8].js'
            },
            miniCssExtractPluginOption: {
                ignoreOrder: true,
                filename: 'css/[name].[hash].css',
                chunkFilename: 'css/[name].[chunkhash].css'
            },
            lessLoaderOption: {
                lessOptions: {
                    modifyVars: {
                        hack: 'true; @import "@/common/assets/css/variables.less";'
                    }
                }
            },
            postcss: {
                autoprefixer: {
                    enable: true,
                    config: {}
                },
                cssModules: {
                    enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
                    config: {
                        namingPattern: 'module', // 转换模式，取值为 global/module
                        generateScopedName: '[name]__[local]___[hash:base64:5]'
                    }
                }
            },
            webpackChain(chain) {
                // 更新输出文件名中的哈希变量
                chain.output.filename('[name].[fullhash:8].js');
                chain.output.chunkFilename('[name].[fullhash:8].js');
                chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin)
                chain.stats({
                    warnings: false, // 关闭警告
                    errors: true,    // 仅显示错误
                });
                chain.merge({
                    devServer: {
                        client: {
                            overlay: false, // 关闭 Webpack overlay，真实有效
                        },
                    },
                    performance: {
                        hints: false
                    },
                    module: {
                        rules: [{
                            test: /\.(js|jsx|ts\tsx)$/,
                            include: /(node_modules|bower_components)/,
                            use: {
                                loader: "babel-loader", options: {
                                    presets: ["@babel/preset-env"]
                                }
                            }
                        }]
                    }
                })
            }
        },
    }
    if (process.env.NODE_ENV === 'development') {
        // 本地开发构建配置（不混淆压缩）
        return merge({}, baseConfig, devConfig)
    }
    // 生产构建配置（默认开启压缩混淆等）
    return merge({}, baseConfig, prodConfig)
})
